<template>
  <view class="page-container">
    <!-- 统计卡片 -->
    <view class="stats-container">
      <view class="stats-card">
        <view class="stats-item">
          <text class="stats-value">{{ todayStats.verify_count || 0 }}</text>
          <text class="stats-label">今日核销</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">{{ todayStats.success_rate || '0%' }}</text>
          <text class="stats-label">成功率</text>
        </view>
        <view class="stats-item">
          <text class="stats-value">{{ todayStats.total_amount || 0 }}</text>
          <text class="stats-label">核销金额</text>
        </view>
      </view>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions">
      <view class="action-card" @click="goToScan">
        <view class="action-icon scan-icon">
          <uni-icons type="scan" size="32" color="#fff"></uni-icons>
        </view>
        <view class="action-content">
          <text class="action-title">扫码核销</text>
          <text class="action-desc">扫描优惠券二维码进行核销</text>
        </view>
        <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="action-card" @click="goToManualVerify">
        <view class="action-icon manual-icon">
          <uni-icons type="compose" size="32" color="#fff"></uni-icons>
        </view>
        <view class="action-content">
          <text class="action-title">手动核销</text>
          <text class="action-desc">输入优惠券码进行手动核销</text>
        </view>
        <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 筛选标签 -->
    <view class="tabs-container">
      <view
        v-for="tab in verifyStatusTabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: queryParams.status === tab.value }"
        @click="handleTabChange(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 核销记录列表 -->
    <scroll-view scroll-y class="list-scroll" @scrolltolower="handleScrollToLower">
      <view v-if="!loading && verifyRecords.length === 0" class="empty-container">
        <uni-icons type="folder-opened" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无核销记录</text>
      </view>
      <view v-else>
        <view v-for="record in verifyRecords" :key="record.id" class="verify-card" @click="goToDetail(record.id)">
          <view class="card-header">
            <view class="coupon-info">
              <text class="coupon-name">{{ record.coupon_name }}</text>
              <uni-tag 
                :text="getVerifyStatusText(record.status)" 
                :type="getVerifyStatusType(record.status)" 
                size="small"
              ></uni-tag>
            </view>
            <text class="verify-time">{{ formatTime(record.created_at) }}</text>
          </view>
          
          <view class="card-body">
            <view class="verify-info">
              <view class="info-row">
                <uni-icons type="person" size="14" color="#999"></uni-icons>
                <text class="info-text">核销员: {{ record.verifier_name || '系统' }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="wallet" size="14" color="#999"></uni-icons>
                <text class="info-text">优惠金额: ¥{{ (record.discount_amount || 0) / 100 }}</text>
              </view>
              <view class="info-row" v-if="record.order_no">
                <uni-icons type="list" size="14" color="#999"></uni-icons>
                <text class="info-text">订单号: {{ record.order_no }}</text>
              </view>
            </view>
          </view>
          
          <view class="card-footer" v-if="record.remark">
            <text class="remark-text">备注: {{ record.remark }}</text>
          </view>
        </view>
      </view>
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { onPullDownRefresh, onReachBottom, onLoad } from '@dcloudio/uni-app';
import { fetchVerifyRecords } from '@/api/coupon';
import moment from 'moment';

// 核销状态枚举
enum VerifyStatus {
  Success = 1,  // 成功
  Failed = 0,   // 失败
  Pending = 2   // 待处理
}

interface VerifyRecord {
  id: number;
  coupon_id: number;
  coupon_name: string;
  coupon_code: string;
  status: VerifyStatus;
  verifier_id?: number;
  verifier_name?: string;
  discount_amount?: number;
  order_no?: string;
  remark?: string;
  created_at: number;
}

interface VerifyQuery {
  page: number;
  pageSize: number;
  status?: VerifyStatus;
  start_date?: string;
  end_date?: string;
}

const verifyRecords = ref<VerifyRecord[]>([]);
const loading = ref(true);
const queryParams = reactive<VerifyQuery>({
  page: 1,
  pageSize: 10,
  status: undefined,
});
const total = ref(0);
const loadMoreStatus = ref('more');
const todayStats = ref<any>({});

const verifyStatusTabs = [
  { label: '全部', value: undefined },
  { label: '成功', value: VerifyStatus.Success },
  { label: '失败', value: VerifyStatus.Failed },
  { label: '待处理', value: VerifyStatus.Pending },
];

const getVerifyRecords = async (isRefresh = false) => {
  if (isRefresh) {
    queryParams.page = 1;
  }
  loadMoreStatus.value = 'loading';
  try {
    const res = await fetchVerifyRecords(queryParams);
    if (isRefresh) {
      verifyRecords.value = res.list;
    } else {
      verifyRecords.value = [...verifyRecords.value, ...res.list];
    }
    total.value = res.total;
    if (verifyRecords.value.length >= total.value) {
      loadMoreStatus.value = 'noMore';
    } else {
      loadMoreStatus.value = 'more';
    }
  } catch (error) {
    console.error('获取核销记录失败:', error);
    loadMoreStatus.value = 'more';
    uni.showToast({
      title: '获取记录失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

const getTodayStats = async () => {
  try {
    const today = moment().format('YYYY-MM-DD');
    const res = await fetchVerifyRecords({
      page: 1,
      pageSize: 1,
      start_date: today,
      end_date: today,
      stats: true
    });
    todayStats.value = res.stats || {};
  } catch (error) {
    console.error('获取今日统计失败:', error);
  }
};

const handleTabChange = (status: VerifyStatus | undefined) => {
  queryParams.status = status;
  getVerifyRecords(true);
};

const handleScrollToLower = () => {
  if (loadMoreStatus.value === 'more') {
    queryParams.page = (queryParams.page || 1) + 1;
    getVerifyRecords();
  }
};

const goToScan = () => {
  uni.navigateTo({
    url: '/pages/coupons/verify/scan'
  });
};

const goToManualVerify = () => {
  uni.showModal({
    title: '手动核销',
    editable: true,
    placeholderText: '请输入优惠券码',
    success: (res) => {
      if (res.confirm && res.content) {
        handleManualVerify(res.content);
      }
    }
  });
};

const handleManualVerify = async (code: string) => {
  try {
    uni.showLoading({ title: '核销中...' });
    // 这里应该调用核销API
    // const result = await verifyCouponByCode(code);
    uni.hideLoading();
    uni.showToast({
      title: '核销成功',
      icon: 'success'
    });
    // 刷新列表
    getVerifyRecords(true);
    getTodayStats();
  } catch (error) {
    uni.hideLoading();
    console.error('手动核销失败:', error);
    uni.showToast({
      title: '核销失败',
      icon: 'none'
    });
  }
};

const goToDetail = (id: number) => {
  uni.navigateTo({
    url: `/pages/coupons/verify/detail?id=${id}`
  });
};

const getVerifyStatusText = (status: VerifyStatus) => {
  const statusMap = {
    [VerifyStatus.Success]: '成功',
    [VerifyStatus.Failed]: '失败',
    [VerifyStatus.Pending]: '待处理'
  };
  return statusMap[status] || '未知';
};

const getVerifyStatusType = (status: VerifyStatus) => {
  const typeMap = {
    [VerifyStatus.Success]: 'success',
    [VerifyStatus.Failed]: 'error',
    [VerifyStatus.Pending]: 'warning'
  };
  return typeMap[status] || 'default';
};

const formatTime = (timestamp: number) => {
  return moment(timestamp * 1000).format('MM-DD HH:mm');
};

onLoad(() => {
  getVerifyRecords(true);
  getTodayStats();
});

onPullDownRefresh(() => {
  getVerifyRecords(true);
  getTodayStats();
});

onReachBottom(() => {
  handleScrollToLower();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.stats-container {
  padding: 15px;
  background-color: #fff;
  
  .stats-card {
    display: flex;
    justify-content: space-around;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: var(--border-radius-lg);
    
    .stats-item {
      text-align: center;
      color: #fff;
      
      .stats-value {
        display: block;
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 5px;
      }
      
      .stats-label {
        font-size: 12px;
        opacity: 0.8;
      }
    }
  }
}

.quick-actions {
  padding: 0 15px;
  margin-bottom: 10px;
  
  .action-card {
    display: flex;
    align-items: center;
    background-color: #fff;
    border-radius: var(--border-radius);
    padding: 15px;
    margin-bottom: 10px;
    box-shadow: var(--shadow);
    
    .action-icon {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 15px;
      
      &.scan-icon {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
      }
      
      &.manual-icon {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
      }
    }
    
    .action-content {
      flex: 1;
      
      .action-title {
        display: block;
        font-size: 16px;
        font-weight: bold;
        color: var(--text-color-primary);
        margin-bottom: 5px;
      }
      
      .action-desc {
        font-size: 12px;
        color: var(--text-color-secondary);
      }
    }
  }
}

.tabs-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid var(--border-color);
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 14px;
    color: var(--text-color-secondary);
    position: relative;
    
    &.active {
      color: var(--primary-color);
      font-weight: bold;
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background-color: var(--primary-color);
        border-radius: 2px;
      }
    }
  }
}

.list-scroll {
  flex: 1;
  height: 0;
}

.verify-card {
  background-color: #fff;
  margin: 10px;
  border-radius: var(--border-radius);
  padding: 15px;
  box-shadow: var(--shadow);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
    
    .coupon-info {
      flex: 1;
      
      .coupon-name {
        display: block;
        font-size: 16px;
        font-weight: bold;
        color: var(--text-color-primary);
        margin-bottom: 5px;
      }
    }
    
    .verify-time {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
  
  .card-body {
    padding: 15px 0;
    
    .verify-info {
      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        
        .info-text {
          font-size: 12px;
          color: var(--text-color-secondary);
          margin-left: 8px;
        }
      }
    }
  }
  
  .card-footer {
    padding-top: 10px;
    border-top: 1px solid var(--border-color);
    
    .remark-text {
      font-size: 12px;
      color: var(--text-color-secondary);
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100px;
  
  .empty-text {
    margin-top: 15px;
    color: #999;
  }
}
</style>